from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import logging
from django.core import serializers
from django.db.models import Q
import json, math, re

logger = logging.getLogger('log')

from ..serverEvCfg import httpResponseSignal
# 导入所需的models
from ..models import ptTestRequestTestCase, ptTestRequest, ptTestProject, ptTestGrouping, ptTestDatabase, ptTestHeards
from ..utilService.webSqlExe import ModelData


@csrf_exempt  # 忽略跨域
@api_view(['POST'])
def addCase(request):
    '''
    添加新用例
    '''
    data = json.loads(request.body)
    validForm = data["dynamicValidateForm"]  # 获取前端传回的用例数据
    myCaseId = data["myCase_id"]  # 获取用例id
    try:
        case_name = validForm["case_name"]  # 获取用例名称
        case_request_id = validForm["request_id"]  # 获取用例关联的接口ID
        request_header_param = validForm["headers"]  # 获取用例关联接口的headers内容
        headerData = validForm["headerData"]  # 获取headers的参数内容
        request_data_content = validForm["domains"]  # 获取headers参数内容
        request_other_type = validForm["request_other_type"]  # 用例关联其他接口
        request_relation_content = validForm["request_relation_content"]  # 用例关联其他接口内容
        request_result = validForm["request_result"]  # 用例的请求返回结果（也就是断言结果）
        otherCaseid = validForm["caseid"]  # 关联其他用例ID
        otherCaseidConclusionValue = validForm["caseidConclusionValue"]  # 其他用例的结果取值
        dataType = validForm["dataType"]  # 接口请求类型
        sqlContent = {
            "sqlTrueFlasetype": validForm["sqlTrueFlasetype"],
            "sqlChoice": validForm["sqlChoice"],
            "SQLinput": validForm["SQLinput"],
            "SQLMomentum": validForm["SQLMomentum"],
            "sqlClusionValue": validForm["sqlClusionValue"],
            "sqlTrueFlasetypeLast": validForm["sqlTrueFlasetypeLast"],
            "sqlChoiceLast": validForm["sqlChoiceLast"],
            "SQLinputLast": validForm["SQLinputLast"],
            "SQLMomentumLast": validForm["SQLMomentumLast"],
            "sqlClusionValueLast": validForm["sqlClusionValueLast"]
        }
        if myCaseId == "": # 新增用例
            case = ptTestRequestTestCase(case_name=case_name,
                                         case_request_id=case_request_id,
                                         request_header_param=request_header_param,
                                         headerData=headerData,
                                         request_data_content=request_data_content,
                                         request_other_type=request_other_type,
                                         request_relation_content=request_relation_content,
                                         request_result=request_result,
                                         otherCaseid=otherCaseid,
                                         otherCaseidConclusionValue=otherCaseidConclusionValue,
                                         dataType=dataType,
                                         sqlContent=sqlContent, )
        else:  # 编辑用例
            case = ptTestRequestTestCase.objects.get(case_id=int(myCaseId))
            case.case_name = case_name
            case.case_request_id = case_request_id
            case.request_header_param = request_header_param
            case.headerData = headerData
            case.request_data_content = request_data_content
            case.request_other_type = request_other_type
            case.request_relation_content = request_relation_content
            case.request_result = request_result
            case.otherCaseid = otherCaseid
            case.otherCaseidConclusionValue = otherCaseidConclusionValue
            case.dataType = dataType
            case.sqlContent = sqlContent
        case.save()

        response = httpResponseSignal.httpResponseSignal().getSuccess()
        return JsonResponse(response)
    except EOFError as  e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def getRequesRelatecase(request):
    '''
    获取接口关联测试用例
    '''
    data = json.loads(request.body)
    try:
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        project_request_list = json.loads(serializers.serialize("json", ptTestProject.objects.all()))
        response["project_request_list"] = project_request_list

        gerouplist = json.loads(
            serializers.serialize("json", ptTestGrouping.objects.filter(group_pj_id=data["pro_id"])))
        response["gerouplist"] = gerouplist

        requstlist = json.loads(
            serializers.serialize("json", ptTestRequest.objects.filter(request_group_id=data["groupid"])))
        response["requstlist"] = requstlist

        caselist = json.loads(
            serializers.serialize("json", ptTestRequestTestCase.objects.filter(case_request_id=data["requestid"])))
        response["caselist"] = caselist

        print(response)
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 忽略跨域
@api_view(['POST'])
def getRelatecaseData(request):
    '''
    获取对应接口请求下测试用例详细信息
    '''
    data = eval(json.loads(request.body)["data"])
    pageSize = data["pageSize"]  # 每页个数
    pageNum = data["pageNum"]  # 当前第几页
    try:
        caseAllList = ptTestRequestTestCase.objects.filter(case_request_id=data["requestID"]).order_by("-updata_time")
        caseAllList = caseAllList.filter(Q(case_name__icontains=data["case_name"]) & Q(request_code__icontains=data["request_code"]))
        print(caseAllList)
        caseSizeList = caseAllList[:pageNum * pageSize]  # 获取当前页之前数据
        caseCount = caseAllList.count()  # case总数
        pageCount = math.ceil(caseCount / pageSize)  # 总页数
        print(type(caseSizeList))
        curData = json.loads(serializers.serialize("json", caseSizeList))[pageSize * pageNum - pageSize:pageNum * pageSize]  # 获取当前页数据
        for i in range(len(curData)):  # 获取格式化时间
            creatTime = curData[i]["fields"]["creat_time"]
            updata_time = curData[i]["fields"]["updata_time"]
            curData[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0] + " " + re.split('[TZ.]', creatTime)[1]
            curData[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + \
                                                  re.split('[TZ.]', updata_time)[1]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = curData
        response["countNum"] = pageCount  # 总页数
        response["gourpCount"] = caseCount  # 总数据量
        response["pageNum"] = pageNum  # 当前第几页
        response["pageSize"] = pageSize  # 每页个数
        print(response)
        return JsonResponse(response)
    except EOFError as  e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 忽略跨域
@api_view(['POST'])
def getSingleCase(request):
    '''
    获取单个用例信息
    '''
    data = json.loads(request.body)
    try:
        case = ptTestRequestTestCase.objects.filter(case_id=data["case_id"])
        caseAboutValue = ModelData().dataBaseHandle(case.values()[0])
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["dynamicValidateForm"] = caseAboutValue
        return JsonResponse(response)
    except EOFError as  e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 忽略跨域
@api_view(['POST'])
def deleteCase(request):
    '''
    删除测试用例
    '''
    data = eval(json.loads(request.body)["data"])
    try:
        if data["id"] != "":
            ptTestRequestTestCase.objects.filter(case_id=data["data"]).delete()
            response = httpResponseSignal.httpResponseSignal().getSuccess()
            response["msg"] = "删除成功"
            return JsonResponse(response)
        else:
            response = httpResponseSignal.httpResponseSignal().getFail()
            response["msg"] = "请检查，是否缺少参数"
            return JsonResponse(response)
    except EOFError as  e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


from ..utilService import methods


@csrf_exempt  # 忽略跨域
@api_view(['POST'])
def checkCasePoint(request):
    '''
    用例检查点
    '''
    data = eval(json.loads(request.body)["data"])
    herderList = json.loads(request.body)["herderList"]

    print("data~~:",data)

    for i in range(len(data)):
        data[i]["herderList"] = herderList
    try:
        logger.info("请求接口参数：%s" % (data))
        Result = methods.method().JOBcheckPoint(data) # 提取headers请求信息格式 + 提取关联取值
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        print("Result数据",Result)
        print("Result类型",type(Result))
        response["data"] = Result["data"]
        response["reuslt"] = Result["reuslt"]
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def checkCase(request):
    '''
    检查用例
    '''
    data = json.loads(request.body)
    try:
        logger.info("用例检查，传参%s" % (data))
        resultAll = methods.method().JOBcheckCaseAll(data)
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = resultAll["data"]
        response["reuslt"] = resultAll["reuslt"]
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def getTestDB(request):
    '''
    选择数据库
    '''
    try:
        dbEvn = ptTestDatabase.objects.all()
        list = []
        evnParamsList = dbEvn.values_list("id", "host")
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        for i in range(len(evnParamsList)):
            dictList = {}
            print(evnParamsList[i][0])
            dictList["id"] = evnParamsList[i][0]
            dictList["host"] = evnParamsList[i][1]
            list.append(dictList)
        response["data"] = list
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        return None


@csrf_exempt
@api_view(['POST'])
def getSqlresultValue(request):
    '''
    获取对应sql返回数据
    '''
    data = json.loads(request.body)
    try:
        resultValue = methods.method().getSQLValue(id=data["id"],
                                                   sql=data["sql"],
                                                   SQLMomentum=data["SQLMomentum"],
                                                   resultlist=data["reusltList"])
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = resultValue
        print('return vue data;',response)
        return JsonResponse(response,safe=False)
    except EOFError as e:
        logger.error(e)
        return None


@csrf_exempt
@api_view(['POST'])
def getHeaders(request):  # 获取headers表
    try:
        herdersList = json.loads(serializers.serialize("json", ptTestHeards.objects.all()))
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["herdersList"] = herdersList
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt
@api_view(['POST'])
def assertionCase(request):
    '''
    断言数据结果+状态
    '''
    data = json.loads(request.body)
    try:
        Result = methods.method().AssertionResults(request_result=data["request_result"],
                                                   result=data["finalResult"],
                                                   resultlist=data["FinalValueResult"],
                                                   sqldata=data["sqldata"])
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = Result
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


from ..utilService import exeTestCase


@csrf_exempt
@api_view(['POST'])
def executionCase(request):
    '''
    执行用例
    '''''
    data = json.loads(request.body)
    print(data)
    try:
        Result = exeTestCase.exeTestCase().singleeExecution(data["caseList"])
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = Result
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt
@api_view(['POST'])
def copyCurrentCase(request):  # 复制当前接口内容
    data = eval(json.loads(request.body)["data"])
    try:
        caseOld = ptTestRequestTestCase.objects.get(case_id=data["id"])
        caseOld.case_id = None
        caseOld.save()
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)
